package org.cent.example.mqtt.consumer.config;

import org.cent.example.mqtt.consumer.config.prop.MqttProp;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author: cent
 * @email: 292462859@qq.com
 * @date: 2019/2/13.
 * @description:
 */
@Configuration
@EnableConfigurationProperties({MqttProp.class})
public class MqttConfig {

    @Bean
    public MqttClient mqttClient(MqttProp mqttProp) throws MqttException {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false);
        options.setUserName(mqttProp.getUsername());
        options.setPassword(mqttProp.getPassword().toCharArray());
        options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);

        MqttClient mqttClient = new MqttClient("tcp://"+mqttProp.getHost() + ":" + mqttProp.getPort(), mqttProp.getClientId());
        mqttClient.connect(options);

        return mqttClient;
    }
}
